<?php

declare(strict_types=1);

namespace app\backend\controller\sys;

use app\common\controller\Basic;
use app\common\service\sys\UserService;
use app\common\service\sys\RoleService;
use app\common\service\hrm\CompanyService;
use app\common\service\sys\UserRoleService;

/**
 * 系统用户-控制器
 * @author kaige
 * @Update 2023-08-12
 */
class User extends Basic
{

  // 初始化
  protected function initialize()
  {
    parent::initialize();
    // 当前控制器服务实例化
    $this->service = new UserService();
  }

  /**
   * 列表
   */
  public function index()
  {
    if (request()->isGet()) {
      return json($this->service->_list(input('param.')));
    }
    return _jerr(1000);
  }

  /**
   * 添加
   */
  public function add()
  {
    if ($this->request->isPost()) {
      $data = input('param.');
      //验证输入
      $userValidate = new \app\common\validate\sys\User();
      $revli = $userValidate->check([
        'un' => $data['un'],
        'pwd' => $data['pwd'],
      ]);
      if (!$revli) {
        return _jerr($userValidate->getError());
      }
      return json($this->service->saveUserForm($data));
    }
    if ($this->request->isGet()) {
      return _jok('ok', [
        'companyList' => CompanyService::getCompanyList(),
        'roleList' => (new RoleService())->getListAll()
      ]);
    }
    return _jerr(1000);
  }

  /**
   * 查看
   */
  public function look()
  {
    if ($this->request->isGet()) {
      $id = input('id/d', 0);
      $data = $this->service->getInfoById($id);
      if (!empty($data['avatar'])) {
        $data['avatar_url'] = _img($data['avatar']);
      }
      $data['company_id_name'] = CompanyService::getNameById($data['company_id']);
      $rlist = (new RoleService())->getListAll();
      $urServer = new UserRoleService();
      $smList  = $urServer->getListAll(['user_id' => $data['id']]);
      foreach ($rlist as $k => $v) {
        $checked = false;
        foreach ($smList as $i => $j) {
          if ($j['role_id'] == $v['id']) {
            $checked = true;
            break;
          }
        }
        $rlist[$k]['checked'] = $checked;
      }
      $data['roleList'] = $rlist;
      return _jok('ok', $data);
    }
    return _jerr(1000);
  }

  /**
   * 编辑
   */
  public function edit()
  {
    $data = input('param.');
    if (!isset($data['id']) || empty($data['id'])) {
      return _jerr(1022);
    }
    if ($this->request->isPost()) {
      if ($data['id'] == config('kaige.super_id')) {
        return _jerr('不允许编辑');
      }
      return json($this->service->saveUserForm($data));
    }
    if ($this->request->isGet()) {
      $data = $this->service->getInfoById($data['id']);
      $data['companyList'] = CompanyService::getCompanyList();
      $rlist = (new RoleService())->getListAll();
      $urServer = new UserRoleService();
      $smList  = $urServer->getListAll(['user_id' => $data['id']]);
      foreach ($rlist as $k => $v) {
        $checked = false;
        foreach ($smList as $i => $j) {
          if ($j['role_id'] == $v['id']) {
            $checked = true;
            break;
          }
        }
        $rlist[$k]['checked'] = $checked;
      }
      $data['roleList'] = $rlist;
      if (!empty($data['avatar'])) {
        $data['avatar_url'] = _img($data['avatar']);
      }
      return _jok('ok', $data);
    }
    return _jerr(1000);
  }

  /**
   * 删除
   */
  public function del()
  {
    if (request()->isPost()) {
      $id = input('id/d', 0);
      if ($id === 0) {
        return _jerr(1026);
      }
      if ($id == config('kaige.super_id')) {
        return _jerr('不允许删除');
      }
      $uo = $this->service->delete($id);
      if ($uo) {
        return _jok(1025);
      }
      return _jerr(1026);
    }
    return _jerr(1000);
  }

  /**
   * 获取登录用户信息
   */
  public function getinfo()
  {
    if (request()->isPost()) {
      $user['username']    = $this->user['un'];
      $user['email']       = $this->user['email'];
      $user['nickname']    = $this->user['real_name'];
      $user['phone']       = $this->user['phone'];
      $user['avatar']      = _img($this->user['avatar']);
      $user['create_time'] = $this->user['create_time'];
      $user['last_time']   = time2str($this->user['last_time']);
      // 获取角色权限
      $role = (new RoleService())->getRoleAuth($this->user['id']);
      $user['roles'] = $role['roles'];
      $user['perms'] = $role['perms'];

      return _jok('', $user);
    }
    return _jerr(1000);
  }

  /**
   * 修改密码
   */
  public function editpwd()
  {
    if (request()->isPost()) {
      $id = $this->user['id']; //这里id不是靠传入的，是取自判定 token的
      if (!$id) {
        return _jerr(1026);
      }
      $data = $this->request->post();
      if (isset($data['password']) && empty($data['password'])) {
        return _jerr(1026);
      }
      if (isset($data['newPwd']) && empty($data['newPwd'])) {
        return _jerr(1026);
      }
      if (isset($data['rePwd']) && empty($data['rePwd'])) {
        return _jerr(1026);
      }
      if ($data['rePwd'] !== $data['newPwd']) {
        return _jerr(1026);
      }
      return json($this->service->chengePwd($id, $data['password'], $data['newPwd']));
    }
    if (request()->isGet()) {
      return _jok('ok', [
        'id' => $this->user['id'],
        'real_name' => $this->user['real_name'],
        'username' => $this->user['un']
      ]);
    }
    return _jerr(1000);
  }
}
